﻿using System.Collections.Generic;
using UnityEngine;
//创建带有该脚本的object
namespace ActionSystem.Core.Utils
{
    /// <summary>
    /// 通用对象池,直接生成对象的
    /// 如何一开始就初始化好是个问题?用的时候初始化难免造成一次卡顿
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GameObjectPool<T> where T : MonoBehaviour, IPoolItem
    {
        private const int INIT_DELTA_CAPACITY = 40;
        private static List<T> buffers = new List<T>();
        private static int delta_capacity = INIT_DELTA_CAPACITY;
        
        /// <summary>
        /// 预先初始化对象池，填充元素
        /// </summary>
        /// <param name="capacity">初始容量</param>
        public static void PreInitPool(int capacity= INIT_DELTA_CAPACITY)
        {
            //初始化增加容量
            for (int i = 0; i < capacity; i++)
            {
                //创建
                var obj = new GameObject();
                var t = obj.AddComponent<T>();
                obj.name = typeof(T).Name;
                MonoBehaviour.DontDestroyOnLoad(obj);
                //放入池子中
                t.gameObject.SetActive(false);
                t.IsDeleted = true;
                buffers.Add(t);
            }
        }
        //从池中获取        
        public static T Create()
        {
            T t=null;
            if(buffers.Count == 0)
            {
                PreInitPool(delta_capacity);
                delta_capacity *= 2;
            }
            t = buffers[buffers.Count - 1];
            buffers.RemoveAt(buffers.Count - 1);
            t.gameObject.SetActive(true);            
            t.PoolItemReset();//初始化
            t.IsDeleted = false;
            return t;
        }
        //放入池中
        public static void Delete(T item)
        {
            if (!item.IsDeleted)
            {
                item.gameObject.SetActive(false);
                item.IsDeleted = true;
                MonoBehaviour.DontDestroyOnLoad(item.gameObject);
                buffers.Add(item);
            }            
        }

        public static int PoolCount
        {
            get { return buffers.Count; }
        }
    }

}